package com.xiaoma.common.observer.resume

import android.util.Log
import androidx.lifecycle.LifecycleOwner
import com.xiaoma.common.observer.Observer
import java.util.concurrent.ConcurrentHashMap

/**
 * author: liangjingbo
 * date: 2022/7/30
 * describe: 订阅者是 Resume 状态的时候才能收到回调
 */
open class ResumeObservable<T> {
    private val TAG = "${this.javaClass.simpleName}Tag"
    private val mWrappers = ConcurrentHashMap<Observer<T>, ResumeObserver<T>>()


    /**
     * 订阅
     * @param owner LifecycleOwner
     * @param observer Observer<T> 监听者
     */
    fun observer(
        owner: LifecycleOwner,
        observer: Observer<T>
    ) {
        val wrapper = ResumeObserver(owner, observer, mWrappers)
        if (mWrappers.containsKey(wrapper.observer)) {
            Log.w(TAG, "observer() Cannot add the same observer !!!")
            return
        }
        mWrappers[wrapper.observer] = wrapper
        owner.lifecycle.addObserver(wrapper)
    }

    open fun dispatchValue(value: T) {
        mWrappers.forEach {
            it.value.setData(value)
        }
    }
}